// 全局变量
let conversationId = null;
let chatHistory = [];
let currentServerId = null;

// DOM元素
const userInput = document.getElementById('userInput');
const sendButton = document.getElementById('sendButton');
const chatContainer = document.getElementById('chatContainer');
const clearChatButton = document.getElementById('clearChat');
const toolCallModal = new bootstrap.Modal(document.getElementById('toolCallModal'));
const toolCallDetails = document.getElementById('toolCallDetails');
const currentServerInfo = document.getElementById('currentServerInfo');

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    // 绑定事件
    sendButton.addEventListener('click', sendMessage);
    userInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });
    clearChatButton.addEventListener('click', clearChat);
    
    // 初始化服务器信息显示
    updateServerInfoDisplay();
});

// 更新服务器信息显示
function updateServerInfoDisplay() {
    if (currentServerInfo) {
        if (currentServerId) {
            currentServerInfo.innerHTML = `当前服务器: <span class="badge bg-primary">${currentServerId}</span>`;
            currentServerInfo.style.display = 'block';
        } else {
            currentServerInfo.style.display = 'none';
        }
    }
}

// 发送消息
async function sendMessage() {
    const message = userInput.value.trim();
    if (!message) return;
    
    // 添加用户消息到聊天
    addMessageToChat('user', message);
    userInput.value = '';
    
    // 显示加载状态
    const loadingElement = document.createElement('div');
    loadingElement.className = 'loading';
    chatContainer.appendChild(loadingElement);
    
    try {
        // 发送请求
        const response = await fetch('/api/query', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                query: message,
                conversation_id: conversationId
            })
        });
        
        const result = await response.json();
        
        // 移除加载状态
        if (loadingElement) {
            loadingElement.remove();
        }
        
        if (result.success) {
            // 更新对话ID
            if (result.conversation_id) {
                conversationId = result.conversation_id;
                console.log(`对话ID: ${conversationId}`);
            }
            
            // 处理响应
            processResponse(result.data);
            
            // 检查和更新服务器信息
            if (result.data && result.data.server_id) {
                currentServerId = result.data.server_id;
                updateServerInfoDisplay();
            }
        } else {
            // 处理错误
            addMessageToChat('assistant', `错误: ${result.error || '处理请求时出错'}`);
        }
    } catch (error) {
        // 移除加载状态
        if (loadingElement) {
            loadingElement.remove();
        }
        
        console.error('Error:', error);
        addMessageToChat('assistant', '发生错误，请稍后重试');
    }
}

// 处理响应
function processResponse(data) {
    if (!data) return;
    
    // 显示助手消息
    if (data.messages && data.messages.length > 0) {
        for (const message of data.messages) {
            if (message.role === 'assistant' && message.content) {
                addMessageToChat('assistant', message.content);
            }
        }
    }
    
    // 显示工具调用
    if (data.tool_calls && data.tool_calls.length > 0) {
        for (const toolCall of data.tool_calls) {
            addToolCallToChat(toolCall);
        }
    }
    
    // 滚动到底部
    scrollToBottom();
}

// 添加消息到聊天
function addMessageToChat(role, content) {
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${role}-message`;
    
    const contentDiv = document.createElement('div');
    contentDiv.className = 'message-content';
    contentDiv.innerHTML = marked.parse(content);
    
    messageDiv.appendChild(contentDiv);
    chatContainer.appendChild(messageDiv);
    
    // 保存到历史记录
    chatHistory.push({ role, content });
    
    // 滚动到底部
    scrollToBottom();
}

// 添加工具调用到聊天
function addToolCallToChat(toolCall) {
    const toolCallDiv = document.createElement('div');
    toolCallDiv.className = 'tool-call';
    toolCallDiv.innerHTML = `
        <div><strong>工具调用:</strong> ${toolCall.tool}</div>
        <div class="text-muted small">点击查看详情</div>
    `;
    
    // 点击查看详情
    toolCallDiv.addEventListener('click', () => {
        showToolCallDetails(toolCall);
    });
    
    chatContainer.appendChild(toolCallDiv);
}

// 显示工具调用详情
function showToolCallDetails(toolCall) {
    toolCallDetails.innerHTML = `
        <h6>工具: ${toolCall.tool}</h6>
        <div class="mb-3">
            <h6>参数:</h6>
            <pre><code>${formatJSON(toolCall.args)}</code></pre>
        </div>
        <div>
            <h6>结果:</h6>
            <pre><code>${formatJSON(toolCall.result)}</code></pre>
        </div>
    `;
    
    toolCallModal.show();
}

// 格式化JSON
function formatJSON(obj) {
    return JSON.stringify(obj, null, 2)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, (match) => {
            let cls = 'json-number';
            if (/^"/.test(match)) {
                if (/:$/.test(match)) {
                    cls = 'json-key';
                } else {
                    cls = 'json-string';
                }
            } else if (/true|false/.test(match)) {
                cls = 'json-boolean';
            } else if (/null/.test(match)) {
                cls = 'json-null';
            }
            return `<span class="${cls}">${match}</span>`;
        });
}

// 清空聊天
function clearChat() {
    chatContainer.innerHTML = '';
    chatHistory = [];
    conversationId = null;
    currentServerId = null;
    updateServerInfoDisplay();
    console.log('已清空对话历史和对话ID');
    
    // 添加欢迎信息
    const welcomeDiv = document.createElement('div');
    welcomeDiv.className = 'welcome-message text-center py-5';
    welcomeDiv.innerHTML = `
        <h3>欢迎使用MCP智能助手</h3>
        <p class="text-muted">
            请输入您的问题，助手会自动选择合适的工具帮您解决问题。
        </p>
    `;
    chatContainer.appendChild(welcomeDiv);
}

// 滚动到底部
function scrollToBottom() {
    chatContainer.scrollTop = chatContainer.scrollHeight;
}